package payment;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码生成工具
 * @author 胥锦灏
 */
public class QRCodeUtils {
    private static final int SIDE = 256;
    private static final int FRONT_COLOR = 0x000000;
    private static final int BACKGROUND_COLOR = 0xffffff;

    /**
     * 用文本信息生成二维码并输出到缓冲区
     * @param content 二维码信息
     * @return 图形缓冲区
     * @throws WriterException 二维码无法生成时抛出
     */
    private static BufferedImage getBufferedImage(String content) throws WriterException {
        System.out.println("[QRCodeUtils] [gen] 生成二维码，内容：" + content);
        HashMap<EncodeHintType, Object> hints = new HashMap<>(3);
        // 编码字符集
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, SIDE, SIDE, hints);
        BufferedImage bufferedImage = new BufferedImage(SIDE, SIDE, BufferedImage.TYPE_INT_BGR);

        for (int x = 0; x < SIDE; x++)
            for (int y = 0; y < SIDE; y++)
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
        return bufferedImage;
    }

    public static boolean createCodeToOutputStream(String content, OutputStream outputStream) {
        if (content == null || content.trim().equals(""))
            return false;
        
        try {
            BufferedImage bufferedImage = getBufferedImage(content);
            ImageIO.write(bufferedImage, "png", outputStream);
            return true;
        } catch (WriterException e) {
            System.err.println("[QRCodeUtils] [Output] " + e.getMessage() + ", content: " + content);
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            System.err.println("[QRCodeUtils] [Output] " + e.getMessage());
            return false;
        }
    }
}
